<template>
  <form
    class="form-page form-page-item-edit"
    v-loading.fullscreen.lock="loadingPage"
    v-if="showFrom"
  >
    <form-builder ref="form" :value="form">
      <form-item ref="formParent"  v-if="canChooseDept" :label="$t('common.fields.parentDepartment.displayName')" validation>
        <form-select ref="vParent" :disabled-just-for-select="true" v-show="false" :value="form.parent" :field="filedMap.parent" />
        <biz-team-select
          :value="form.parent"
          :type-service-provider="typeServiceProvider"
          collapse
          @input="updateForm"
        />
      </form-item>
      <form-item :label="$t('common.label.departmentName')" :validation="checkName">
        <form-text :field="filedMap.tagName" v-model="form.tagName" />
      </form-item>
      <form-item :label="$t('common.label.departmentDesc')" validation>
        <form-textarea
          :field="filedMap.description"
          v-model="form.description"
        />
      </form-item>
      <form-item :label="$t('common.label.DepartmentHeads')" validation>
        <form-user
          :field="filedMap.teamLeaders"
          v-model="form.teamLeaders"
          max="10"
          multiple
          :type-service-provider="0"
        />
        <!-- <team-user-select
          v-if="action == 'edit'"
          :field="filedMap.teamLeaders"
          :fetch="fetchTeamUser"
          v-model="form.teamLeaders"
        /> -->
      </form-item>
      <form-item :label="$t('common.base.managerPermission')">
        <div class="team-form-role-tip">
          <input type="checkbox" checked disabled />
          {{$t('common.label.partmentManage')}}
        </div>
      </form-item>
      <form-item :label="$t('common.label.contactMethod')" validation>
        <form-phone :field="filedMap.phone" v-model="form.phone" />
      </form-item>
      <form-item :label="$t('common.label.departmentLocation')" validation>
        <form-address
          :field="filedMap.tagAddress"
          v-model="form.tagAddress"
          :placeholder="$t('common.fields.serviceProviderRegisterAddress.placeholder')"
        />
      </form-item>
      <form-item :label="$t('common.label.territory')" :validation="checkPlace">
        <team-places
          :field="filedMap.tagPlaceList"
          v-model="form.tagPlaceList"
        />
      </form-item>
    </form-builder>
  </form>
</template>

<script>
import * as TeamApi from '@src/api/TeamApi';

import _ from 'lodash';
import qs from 'qs';
/* mixins */
import VersionMixin from '@src/mixins/versionMixin/index.ts';
import FormMixin from '@src/component/form/mixin/form';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
const { internationalGray } = useFormMultiLanguage()

let tag = {},
  isRoot = false;
export default {
  name: 'team-edit',
  mixins: [VersionMixin],
  props: {
    initData: {
      type: Object,
      default: () => ({})
    },
    // 服务商 控制左边树 【0组织架构】 【1服务商】 【''全部】 默认和之前逻辑一样
    typeServiceProvider: {
      type: Number | String,
      default: ''
    },
    pageType:{
      type: String,
      default: ''
    },
    parentDept:{
      type: Object,
      default: () => ({})
    },
  },
  watch: {
    initData: {
      handler(val) {
        this.initData = val;
        this.init();
      },
      deep: true
    }
  },
  data() {
    return {
      action: '',
      pending: false,

      filedMap: {
        parent:{
          displayName: this.$t('common.fields.parentDepartment.displayName'),
          fieldName: 'parent',
          formType: 'select',
          isNull: 0,
          disabled: false
        },
        tagName: {
          displayName: this.$t('common.label.departmentName'),
          fieldName: 'tagName',
          formType: 'text',
          placeHolder: this.$t('common.placeholder.limitInput', {limit: '20'}),
          isNull: 0,
          disabled: false
        },
        description: {
          displayName: this.$t('common.label.departmentDesc'),
          fieldName: 'description',
          formType: 'textarea',
          isNull: 1
        },
        teamLeaders: {
          displayName: this.$t('common.label.DepartmentHeads'),
          fieldName: 'teamLeaders',
          formType: 'user',
          isNull: 1
        },
        phone: {
          displayName: this.$t('common.label.contactMethod'),
          fieldName: 'phone',
          formType: 'phone',
          isNull: 1
        },
        tagAddress: {
          displayName: this.$t('common.label.departmentLocation'),
          fieldName: 'tagAddress',
          formType: 'address',
          isNull: 1
        },
        tagPlaceList: {
          displayName: this.$t('common.label.territory'),
          fieldName: 'tagPlaceList',
          formType: 'area',
          isNull: 1
        }
      },
      form: {
        tagName: '',
        description: '',
        teamLeaders: [],
        teamLeaderRole: false,
        tagPlaceList: [],
        parent:[]
      },
      id: '',
      loadingPage: false,
      parent: {}, // 主部门信息
      teamData: {},
      users: [], // 用户
      showFrom: true,
      internationalGray,
    };
  },
  computed: {
    /* 是否是 新建部门 */
    isCreate() {
      return this.action != 'edit';
    },
    haveParent(){
      return this.initData?.tag?.parentId
    },
    canChooseDept(){
      return this.pageType == 'dept' && (this.haveParent || (!this.haveParent && this.isCreate))
    }
  },
  methods: {
    /** 自定义验证团队名称 */
    checkName(value, field, changeStatus) {
      return new Promise((resolve, reject) => {
        if (value.length > 100) {
          changeStatus(false);
          return resolve(this.$t('common.validate.maxLen', {limit:100}));
        }
        this.remoteCheckName(
          { id: this.id , field: 'name', value },
          resolve,
          changeStatus
        );
      });
    },
    remoteCheckName: _.debounce(function(params, resolve, changeStatus) {
      changeStatus(true);
      return TeamApi.checkUnique(params)
        .then(validate => {
          changeStatus(false);
          return resolve(validate ? null : this.$t('common.validate.departmrntNameRepeat'));
        })
        .catch(err => console.error(err));
    }, 500),

    checkPlace() {
      return new Promise((resolve, reject) => {
        let tagPlaceList = this.form.tagPlaceList || [];
        let message = null;

        let isRepeat = this.checkPlaceRepeat();

        if (isRepeat) {
          message = this.$t('common.validate.territoryRepeat');
        } else {
          if(!this.internationalGray) {
            for (let i = 0; i < tagPlaceList.length; i++) {
              let place = tagPlaceList[i] || {};
              if (!place.province) {
                message = this.$t('common.validate.territoryComplement');
                break;
              }
            }
          }

        }

        resolve(message);
      });
    },
    // 验证负责区域是否重复
    checkPlaceRepeat() {
      let tagPlaceList = this.form.tagPlaceList || [];
      let isRepeat = false;

      for (let i = 0; i < tagPlaceList.length; i++) {
        let item = tagPlaceList[i];
        const address = [item.province,item.city,item.dist]
        if(this.internationalGray) {
          address.unshift(item.country)
        }
        let place = address.filter(Boolean).join('')
        // let place = `${item.province}${item.city}${item.dist}`;

        if (place) {
          for (let j = 0; j < tagPlaceList.length; j++) {
            if (j == i) continue;

            let tItem = tagPlaceList[j];
            const tAddress = [ tItem.province,tItem.city,tItem.dist]
            if(this.internationalGray) {
              tAddress.unshift(tItem.country)
            }
            let tPlace = tAddress.filter(Boolean).join('');

            if (place == tPlace) {
              isRepeat = true;
              break;
            }
          }
        }
      }
      return isRepeat;
    },
    async fetchTeamUser(params) {
      return TeamApi.userList({ ...params, ...{ tagId: this.id } });
    },

    /* 打包给服务端的数据 */
    packData(data) {
      let params = {};
      if(data.parent?.length){
        params.parentId = data.parent[0].id
      }
      params.tagName = data.tagName;
      params.description = data.description;
      params.teamLeaders = data.teamLeaders;
      params.phone = data.phone;
      params.tagAddress = data.tagAddress;
      if (!params.tagAddress.hasOwnProperty('addressType')) {
        params.tagAddress.addressType = 1;
      }

      params.tagPlaceList = data.tagPlaceList || [];
      params.teamLeaders = data.teamLeaders;

      return params;
    },
    unPackData(data) {
      let form = {};
      if(data){
         data.tagAddress = {}
        data.tagAddress.address = data.address || '';
        data.tagAddress.addressType = 1;
        data.tagAddress.city = data.city || '';
        data.tagAddress.dist = data.dist || '';
        data.tagAddress.latitude = data.latitude;
        data.tagAddress.longitude = data.longitude;
        data.tagAddress.province = data.province || '';
        data.tagAddress.country = data.country || '';
      }
      if(data && data.tagPlaceList && data.tagPlaceList.length){
         let arr = [];
         data.tagPlaceList.forEach(item=>{
           let obj = {}
           obj.city = item.city
           obj.dist = item.dist
           obj.province = item.province
           obj.country = item.country
           arr.push(obj)
         })
         form.tagPlaceList = arr
      }else{
        form.tagPlaceList = []
      }
      form.tagName = data.tagName;
      form.description = data.description;
      form.teamLeaders = data.teamLeaders || [];
      form.teamLeaderRole = true;
      form.phone = data.phone;
      form.tagAddress = data.tagAddress || {};
      let partentId = !this.isCreate ? data?.parentId : this.parentDept?.id
      let partentName = !this.isCreate ? data?.parentName : this.parentDept?.tagName
      form.parent = (this.canChooseDept && [{id: partentId, tagName: partentName || ''}]) || []
      // form.tagPlaceList = data.tagPlaceList || [];
      return form;
    },
    reloadTab() {
      let fromId = window.frameElement.getAttribute('fromid');

      this.$platform.refreshTab(fromId);
    },
    submit() {
      if (isRoot === 'true' && tag.tagName != this.form.tagName) {
        return this.$platform.alert(this.$t('common.validate.rootDepartmrntUnmodify'));
      }
      // fix:9316 前端加一下限制  地址长度不超过120个字符
      if (this.form.tagAddress?.address?.length > 120) {
        return this.$platform.alert(this.$t('common.validate.addressLengLimit'));
      }
      return this.$refs.form
        .validate()
        .then(valid => {
          if (!valid) return;

          const params = this.packData(this.form);
          const obj = {
            action: this.action,
            params
          };
          return obj;
        })
        .catch(err => {
          // console.error(err);
        });
    },
    init() {
      let query = qs.parse(window.location.search.substr(1));
      tag = this.initData.tag || {};
      this.action = tag.id ? 'edit' : 'create';
      this.id = tag.id || '';
      this.showFrom = false;
      if (tag.id) {
        this.form = {};
      }
      this.$nextTick(function() {
        this.showFrom = true;
        this.form = this.unPackData(tag);
      });
      this.parent.id = query.pid;
      this.parent.tagName = query.pname;
      isRoot = query.isRoot;
      // 根部门名称不能编辑
      if (isRoot === 'true' && tag.id) this.filedMap.tagName.disabled = true;

      // if (this.isCreate) {
      //   // 检查版本数量限制
      //   this.checkNumExceedLimitBeforeHandler
      //     && this.checkNumExceedLimitBeforeHandler(
      //       TenantDataLimitSourceEnum.Tag,
      //       TenantDataLimitTypeEnum.Tag
      //     );
      // }
    },
    updateForm(info){
      this.$set(this.form, 'parent', info)
      this.$nextTick(()=>{
        console.log(this.$refs.vParent, 'this.$refs.vParent')
        this.$refs.vParent.input(info)
      })
    }
  },
  created() {
    this.init();
  },
  components: {
    'team-places': {
      mixins: [FormMixin],
      props: {
        value: {
          type: Array,
          default: () => []
        }
      },
      methods: {
        addPlace() {
          this.value.push({});
          this.$emit('input', this.value);
        },
        removePlace(item) {
          let index = this.value.indexOf(item);
          if (index >= 0) this.value.splice(index, 1);

          this.$emit('input', this.value);
        },

        update(item, value = {}) {
          let { country, province, city, dist } = value;

          this.$set(item, 'country', country || '');
          this.$set(item, 'province', province);
          this.$set(item, 'city', city);
          this.$set(item, 'dist', dist);
          this.$emit('input', this.value);
        },

        renderDistPicker(item){
          return (
            <span>
              <base-dist  value={item}  showOneLine={true} onInput={e => this.update(item, e)}/> 
            </span>
          )
        },
      },

      render(h) {
        return (
          <div class="team-form-places">
            <div class="team-form-places-header">
              <p>{this.$t('common.validate.setTerritory')}</p>
              <button
                type="button"
                class="btn-text"
                onClick={e => this.addPlace()}
              >
                <i class="iconfont icon-add" />
                {this.$t('common.base.add2')}
              </button>
            </div>
            {this.value.map((item, index) => (
              <div
                class={['team-form-place', item.success ? 'is-success' : null]}
                key={index}
              >
                { this.renderDistPicker(item) }
                <button
                  type="button"
                  class="btn-text"
                  onClick={e => this.removePlace(item)}
                >
                  {this.$t('common.base.delete')}
                </button>
              </div>
            ))}
          </div>
        );
      }
    },
    'team-user-select': {
      name: 'team-user-select',
      mixins: [FormMixin],
      props: {
        value: {
          type: Array,
          default: () => []
        },
        fetch: Function
      },
      methods: {
        input(value) {
          this.$emit('input', value);
        }
      },
      render(h) {
        return (
          <biz-user-select
            value={this.value}
            onInput={e => this.input(e)}
            fetch={this.fetch}
            multiple
          />
        );
      }
    }
  }
};
</script>

<style lang="scss">
body {
  padding: 10px;
}

.team-form-role-tip {
  height: 32px;
  display: flex;
  align-items: center;
  color: $text-color-secondary;

  input {
    margin-right: 5px;
  }
}

.team-form-places {
  span:first-child{
    width:100%;
  }
  p {
    padding: 4px 0;
    margin: 0;
    line-height: 24px;
    color: $text-color-secondary;
  }
}

.team-form-places-header {
  padding: 4px 0;
  color: $text-color-secondary;
  display: flex;
  flex-flow: row nowrap;

  p {
    flex: 1;
    margin: 0;
    line-height: 24px;
  }

  .btn-text {
    color: $color-primary;

    i {
      font-size: 12px;
      margin-right: 5px;
    }
  }
}

.team-form-place {
  display: flex;
  flex-flow: row nowrap;

  .base-dist-picker {
    flex: 1;
    margin-right: 5px;

    & > .el-cascader {
      width: 100%;
    }
  }

  & + .team-form-place {
    margin-top: 5px;
  }

  .btn-text {
    font-size: 13px;
    color: $color-danger;
  }
}
.form-page-item-edit.form-page .form-builder{
  max-width:700px!important;
  width:100%;
  box-sizing: border-box;
  padding:10px 24px!important
}
.form-page-item-edit .form-builder .form-item {
  flex-direction: column;
}
.form-page-item-edit .form-builder .form-item-label {
  padding-left: 0;
  padding-right: 0;
}
.form-item.err :not(.is-success) {
  .biz-team-select{
    border-color: #f56c6c !important;
  }
}
.biz-team-select p{
  padding-left:0 !important;
}
</style>
